package com.own.component.common.util.encrypt.util;

import com.own.component.common.util.encrypt.BaseEncryptUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Md5Util
 *
 * @author chenxueli
 * @date 2020/4/20 16:08
 */
@Slf4j
public class Md5Util implements BaseEncryptUtil {

    /**
     * 加密
     *
     * @param content 加密内容
     * @return 加密后的内容
     */
    @Override
    public String encrypt(String content) {
        String result;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // update处理
            md.update(content.getBytes(StandardCharsets.UTF_8));
            // 调用该方法完成计算
            byte[] encryptContext = md.digest();
            int i;
            StringBuilder builder = new StringBuilder();
            for (byte b : encryptContext) {
                // 做相应的转化（十六进制）
                i = b;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    builder.append("0");
                }
                builder.append(Integer.toHexString(i));
            }
            result = builder.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("md5 encrypt error");
            throw new RuntimeException("加密异常");
        }
        return result;
    }

}
